/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package InfoMat;

import java.io.*;
import javax.microedition.io.*;
import javax.microedition.io.file.*;
import sUtils.*;

public class RSSReader {
    String url = "";
    String tag[] = new String[32];
    String name;
    boolean utf8 = false;
    boolean firstRead = false;
    Log log = new Log(1);

    public RSSReader()
    {
        log.open("/filesystem/rsslog.log");
    }

    public void setURL( NewsStorage st, String u, String n, boolean encoding )
    {
        url = u;
        name = n;
        utf8 = encoding;
        firstRead = true;
        st.clear(n+ " (Offline)");
    }

    public boolean readRSS( NewsStorage st, boolean offline )
    {
       if (url.equals("")) return false;
       InputStream is = null;
       OutputStream os = null;
       int len = 0;
       boolean rc = false;
       String path = "file:///filesystem/" + name + ".htm";
       try {
            FileConnection fc = (FileConnection)Connector.open(path);
            len = (int)(fc.fileSize());

            if (offline && fc.exists())
            {
                is = fc.openDataInputStream();
                rc = is!=null;
            }
            else
            {
                HttpConnection hc = (HttpConnection)Connector.open(url);
                int response = hc.getResponseCode();

                rc = response==200;
                if (rc)
                {
                    if ( (is = hc.openInputStream())!=null )
                    {
                        if (fc.exists()) fc.truncate(0); else fc.create();
                        os = fc.openOutputStream();
                        rc = true;
                        len = (int)hc.getLength();
                        offline = false;
                    } else rc = false;
                }
                if (!rc && fc.exists())
                {
                    is = fc.openDataInputStream();
                    rc = is!=null;
                    offline = true;
                }
            }
            st.reset( name + (offline ? " (Offline)" : " (Online)") );
            rc = internalReadRSS( st, is, os, len );

        }
        catch(Exception e) { rc=false; }

        if (firstRead) { firstRead=false; st.setFirstRead(); }
        return rc;
    }


    public boolean internalReadRSS( NewsStorage st, InputStream is, OutputStream os, int len )
    {
       byte rss[] = null;
       boolean rc = false;
       try {

            int bufsize = 512000;
            rss = (len>0) ? new byte [len] : new byte[bufsize];
            int i=0, size=0, pos=0, utf8c=0; char c=0;
            boolean isItem=false, isTag=false, end=false;
            String currentTag = "", title="", desc="", img="";
            StringBuffer cText = new StringBuffer(50);
            boolean isAnd = false;
            int nAndChar = 0;
            int andChar = 0;

            while ((pos<len || len<0) && !end)
            {

                size = len<0 ? (bufsize-pos) : len-pos; if (size>256) size=256;
                if (size<0) break;
                size = is.read( rss, pos, size );
                if (size<=0) break;
                for ( i=0; i<size; pos++,i++ )
                {
                    c=(char)(((int)rss[pos])&0xff);
                    if (c=='<')
                    {
                        currentTag = "";
                        isTag = true;
                    }
                    else
                    if (c=='>')
                    {
                        if (currentTag.equals("/rss")) end=true;
                        if (currentTag.equals("item")||currentTag.equals("entry"))
                        {
                            isItem = true;
                        }
                        else
                        if (currentTag.equals("/item")||currentTag.equals("/entry"))
                        {
                            st.add( title, desc, img );
                            log.push(title+" | "+desc+" | "+img, true);
                            desc="";
                            img="";
                            title="";
                            isItem = false;
                        } else
                        if (currentTag.equals("?xml"))
                        {
                            String text = cText.toString().toLowerCase();

                            int ISO8859_POS = text.indexOf("iso-8859");
                            int UTF8_POS = text.indexOf("utf-8");
                            if (ISO8859_POS>0) utf8=false;
                            if (UTF8_POS>0) utf8=true;
                        }
                        else if (isItem)
                        {
                            if (currentTag.equals("/title")) title = cText.toString(); else
                            if (currentTag.equals("enclosure")) img = cText.toString(); else
                            if (currentTag.equals("img")) img = cText.toString(); else
                            if (currentTag.equals("/description")) desc = cText.toString(); else
                            if (currentTag.equals("/content:encoded")) desc = cText.toString(); else
                            if (currentTag.equals("title")||currentTag.equals("description")||currentTag.equals("content:encoded"))
                               cText = new StringBuffer(50);
                         }
                        isTag = false;
                        isAnd = false;
                    }
                    else
                    if (isTag)
                    {
                        if (c==' ') isTag=false; else
                        currentTag = currentTag + c;
                    }
                    else
                    {
                        if (isAnd)
                        {
                            if (c=='#') { nAndChar = 0; andChar=0; } else
                            if (c==';')
                            {
                                if (nAndChar>0)
                                {
                                    cText.append((char)andChar);
                                    isAnd = false;
                                }
                            }
                            else
                            if (nAndChar>=0)
                            {
                                andChar = andChar*10 + (c-'0');
                                nAndChar++;
                            }
                        } else
                        if (c=='&') { isAnd=true; nAndChar=-1; andChar=0; } else
                        if (utf8 && ((c&0xc0)==0xc0)) utf8c = c&0x3f; else
                        {
                            if (utf8c>0) { c = (char)(((utf8c<<6)|(c&0x3f))); utf8c=0; }
                            cText.append(c);
                        }
                    }
                }
            }
            if (os!=null) os.write(rss,0,pos);

        } catch(Exception e) { rc=false; }
        if (firstRead) { firstRead=false; st.setFirstRead(); }
        return rc;
    }

}
